package model

import (
	"fmt"
	"github.com/go-ini/ini"
	"github.com/gookit/color"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"go-movie/parse"
)

var db *gorm.DB

type Database struct {
	Username    string
	Password    string
	Host        string
	DbName      string
	TablePrefix string
}


var cfg *ini.File

var database = &Database{}

func Setup() {
	var err error
	cfg, err = ini.Load("conf/app.ini")
	if err != nil {
		color.Error.Printf("Fail to parse 'conf/app.ini': %v \n", err)
	}

	mapTo("database", database)

	addr := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=true",
		database.Username,
		database.Password,
		database.Host,
		database.DbName)

	db, err = gorm.Open("mysql", addr)
	if err != nil {
		color.Error.Printf("gorm.Open.err: %v\n", err)
	}

	db.SingularTable(true)
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return database.TablePrefix + defaultTableName
	}
}

func mapTo(section string, v interface{}){
	err := cfg.Section(section).MapTo(v)
	if err!=nil{
		color.Error.Printf("Cfg.MapTo err: %v", err)
	}
}

//添加数据
func Add(movies []parse.DoubanMovie) {
	for index, movie := range movies {
		if err := db.Create(&movie).Error; err != nil {
			color.Error.Printf("db.Create index: %d, err: %v\n", index, err)
		}
	}
}

func CloseDB() {
	db.Close()
}
